function despread_symbols = despread_data(received_signal, spreading_code, num_symbols)
% despread_data - 对接收的扩频信号进行解扩
%
% 输入参数:
%   received_signal - 接收的CDMA信号
%   spreading_code - 解扩用的扩频码
%   num_symbols    - 符号数量
%
% 输出参数:
%   despread_symbols - 解扩后的符号

% 获取扩频因子
spreading_factor = length(spreading_code);

% 初始化解扩后的符号
despread_symbols = zeros(1, num_symbols);

% 对每个符号进行解扩
for i = 1:num_symbols
    % 计算当前符号对应的芯片序列的起始和结束位置
    start_idx = (i-1) * spreading_factor + 1;
    end_idx = i * spreading_factor;
    
    % 确保索引不超出接收信号长度
    if end_idx <= length(received_signal)
        % 取出对应的芯片序列
        chips = received_signal(start_idx:end_idx);
        
        % 解扩：与扩频码相乘并求和
        despread_symbols(i) = sum(chips .* spreading_code) / spreading_factor;
    else
        warning('解扩过程中索引超出范围，可能是接收信号长度不足');
        break;
    end
end

% RAKE接收机概念实现（简化版）
% 在实际的CDMA系统中，RAKE接收机用于处理多径效应
rake_processing = false;
if rake_processing
    % 定义多径延迟（与发送端多径模型对应）
    path_delays = [0, 5, 15];
    
    % 为每个路径准备一个解扩符号集
    rake_fingers = zeros(length(path_delays), num_symbols);
    
    for path = 1:length(path_delays)
        delay = path_delays(path);
        
        % 对延迟后的信号进行解扩
        delayed_signal = [zeros(1, delay) received_signal(1:end-delay)];
        
        for i = 1:num_symbols
            start_idx = (i-1) * spreading_factor + 1;
            end_idx = i * spreading_factor;
            
            if end_idx <= length(delayed_signal)
                chips = delayed_signal(start_idx:end_idx);
                rake_fingers(path, i) = sum(chips .* spreading_code) / spreading_factor;
            end
        end
    end
    
    % 合并RAKE接收机的各路径结果（最大比合并）
    despread_symbols = sum(rake_fingers, 1);
end

end 